<?php
/*
 * @Created by: wangchengcheng
 * @Author: wangchengcheng
 * @Date: 2020-01-07 18:59:22
 * @LastEditors  : wangchengcheng
 * @LastEditTime : 2020-01-07 20:13:41
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\Category\Store;
use App\Http\Requests\Category\Update;
use App\Models\Category;

class CategoryController extends Controller
{
    /**
     * 分类列表
     * 
     * @return Response
     */
    public function index()
    {
        $data = Category::withTrashed()->orderBy('sort')->get();
        $assign = compact('data');
        
        return view('admin.category.index', $assign);
    }

    /**
     * 创建分类视图
     * 
     * @return Response
     */
    public function create()
    {
        return view('admin.category.create');
    }

    /**
     * 创建分类
     * 
     * @param $request
     * 
     * @return RedirectResponse
     */
    public function store(Store $request)
    {
        $data = Category::create($request->except('_token', 's'));

        return redirect()->back();
    }
    
    /**
     * 修改分类视图
     * 
     * @param $id
     * 
     * @return Response
     */
    public function edit($id)
    {
        $data = Category::withTrashed()->find($id);
        $assign = compact('data');
        
        return view('admin.category.edit', $assign);
    }

    /**
     * 修改分类
     * 
     * @param $request
     * @param $id
     * 
     * @return RedirectResponse
     */
    public function update(Update $request, $id)
    {
        $data = Category::withTrashed()->find($id)->update($request->except('_token', 's'));

        return redirect()->back();
    }

    /**
     * 删除分类
     * 
     * @param $id
     * 
     * @return Reponse
     */
    public function destroy($id)
    {
        Category::destroy($id);

        return redirect()->back();
    }

    /**
     * 恢复删除的分类
     * 
     * @param $id
     */
    public function restore($id)
    {
        Category::onlyTrashed()->find($id)->restore();

        return redirect()->back();
    }

    /**
     * 彻底删除分类
     * 
     * @param $id
     */
    public function forceDelete($id)
    {
        Category::onlyTrashed()->find($id)->forceDelete();

        return redirect()->back();
    }

    /**
     * 排序
     * 
     * @param $request
     * 
     * @return RedirectResponse
     */
    public function sort(Request $request, Category $categoryModel)
    {
        $data = $request->except('_token', 's');

        $updateData = [];
        foreach($data as $k => $v){
            $updateData[] = [
                'id'    => $k,
                'sort'  => $v,
            ];
        }
        $categoryModel->updateBatch($updateData);
        
        return redirect()->back();
    }
}
